#!/bin/bash
set -eux

DEBUG=${DEBUG:-"0"}
RACE=${RACE:-"0"}
PUBLISH=${PUBLISH:-"0"}

proj_root=$(dirname $(dirname $(realpath $0)))
cd $proj_root

# load func
. $proj_root/scripts/covert_arch.sh

race_flag=""
if [ "$RACE" != "0" ]; then
    race_flag="-race"
fi

ldflags="-X 'io.plus/test_loss/cmd.GitHash=$(git rev-parse --short=12 HEAD)'"
gcflags=""

race_flag=""
if [ "$DEBUG" == "1" ]; then
    gcflags="all=-N -l"
else
    ldflags="-s -w ${ldflags}"
fi

# -race
#   编译带有运行时，竞争检查的产物，会导致程序运行减慢很多

# -ldflags="-s -w"
#   release 去除各种符号表

# -gcflags="all=-N -l"
#   禁用各种编译优化，用于调试

go env -w GO111MODULE=on
go env -w GOPROXY='http://goproxy.wh.io.plus,https://goproxy.cn,direct'
go env -w CGO_ENABLED=1
go env
go mod tidy -x

for arch in "x86_64" "aarch64"; do
    export GOOS=linux
    export CGO_ENABLED=0

    goarch=$(uname_to_goarch $arch)
    export GOARCH=$goarch
    echo "goarch: $goarch"

    bin_name="test_loss_$arch"
    if [ "$DEBUG" == "1" ]; then
        bin_name="${bin_name}_debug"
    fi
    go build ${race_flag} -ldflags="${ldflags}" -gcflags="${gcflags}" -o $proj_root/output/"${bin_name}" cmd/test_loss/test_loss.go
    # 发布
    if [ "$PUBLISH" == "1" ]; then
        curl --user 'ioplus:ioplus' \
            -T $proj_root/output/${bin_name} \
            http://mirror.wh.io.plus/test_loss/${bin_name}
    fi
done

# push service file
if [ "$PUBLISH" == "1" ]; then
    bash $proj_root/scripts/publish_service.sh
fi
